package model

import (
	"errors"
	"gorm.io/gorm"
)

type (
	OperationLogsModel struct {
		db *gorm.DB
	}

	OperationLogs struct {
		ID        int64    `gorm:"primarykey" json:"id"`
		UserId    int64    `json:"user_id" gorm:"index;not null"`
		UserName  string   `gorm:"type:varchar(32);index;not null" json:"user_name"`
		Action    string   `json:"action" gorm:"type:varchar(255);default:''"`
		Method    string   `json:"method" gorm:"type:varchar(10)"`
		LogType   string   `json:"log_type" gorm:"type:varchar(10);default:''"` // login logout other
		Title     string   `json:"title" gorm:"type:varchar(100);default:''"`
		Content   string   `json:"-" gorm:"type:text"`
		Ip        string   `json:"ip" gorm:"type:varchar(50);default:''"`
		UserAgent string   `json:"user_agent" gorm:"type:varchar(255);default:''"`
		Status    string   `json:"status" gorm:"type:varchar(255);default:''"` // success failed
		CreatedAt Datetime `json:"created_at" gorm:"index"`
	}
)

func NewOperationLogsModel(db *gorm.DB) *OperationLogsModel {
	return &OperationLogsModel{
		db,
	}
}

func (m *OperationLogsModel) Add(data *OperationLogs) error {
	return m.db.Create(data).Error
}

func (m *OperationLogsModel) FindCount(userId int64, logType, startDate, endDate string) (int64, error) {
	var total int64
	dbSession := m.db.Model(&OperationLogs{})
	dbSession.Where("user_id = ?", userId)
	if logType != "" {
		dbSession.Where("log_type = ?", logType)
	}
	if startDate != "" && endDate != "" {
		dbSession.Where("created_at >= ? and created_at<=?", startDate, endDate)
	}
	err := dbSession.Order("id desc").Count(&total).Error
	return total, err
}

func (m *OperationLogsModel) Find(userId int64, logType, startDate, endDate string, page, size int) ([]OperationLogs, error) {
	list := make([]OperationLogs, 0, 1)
	dbSession := m.db.Model(&OperationLogs{})
	dbSession.Where("user_id = ?", userId)
	if logType != "" {
		dbSession.Where("log_type = ?", logType)
	}
	if startDate != "" && endDate != "" {
		dbSession.Where("created_at >= ? and created_at<=?", startDate, endDate)
	}
	err := dbSession.Order("id desc").Find(&list).Limit(size).Offset((page - 1) * size).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return []OperationLogs{}, err
	}
	return append([]OperationLogs{}, list...), err
}
